package com.ztf0337.mycurriculumdesign.ui.fragment;

import static android.content.Context.MODE_PRIVATE;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ztf0337.mycurriculumdesign.R;
import com.ztf0337.mycurriculumdesign.adapter.ParkingSpaceAdapter;
import com.ztf0337.mycurriculumdesign.entity.ParkingSpace;
import com.ztf0337.mycurriculumdesign.entity.User;
import com.ztf0337.mycurriculumdesign.service.UserService;
import com.ztf0337.mycurriculumdesign.ui.activity.LoginActivity;

import java.util.List;

public class ProfitFragment extends Fragment {

    private RecyclerView rvParkingSpace;
    private ParkingSpaceAdapter adapter;
    private List<ParkingSpace> parkingSpaceList;
    private Context context;
    private UserService userService;
    TextView tv_name_value,tv_phone_value,tv_role_value,tv_login,tv_logout,tv_edit;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profit, container, false);
        context = getContext();
        if (context == null) {
            return view;
        }
        SharedPreferences optionParkLot = context.getSharedPreferences("optionParkLot", Context.MODE_PRIVATE);
        SharedPreferences loginInfo = context.getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
        userService = new UserService(context);



        tv_name_value = view.findViewById(R.id.tv_name_value);
        tv_phone_value = view.findViewById(R.id.tv_phone_value);
        tv_role_value = view.findViewById(R.id.tv_role_value);
        tv_login = view.findViewById(R.id.tv_login);
        tv_logout = view.findViewById(R.id.tv_logout);
        tv_edit = view.findViewById(R.id.tv_edit);

        if (loginInfo.getBoolean("login",false)) {
            User user = userService.getUserById(loginInfo.getLong("user_id", -1L));
            Log.d("测试","用户查找id "+loginInfo.getLong("user_id", -1L));
            if (user != null) {
                tv_logout.setText("退出登陆");
                tv_login.setVisibility(GONE);
                tv_name_value.setText(user.getName());
                tv_phone_value.setText(user.getPhone());
                tv_role_value.setText(user.getRoot() ? "管理员" : "用户");

                tv_edit.setOnClickListener(v -> {
                    updateUser(user);
                });
            } else {
                tv_name_value.setVisibility(GONE);
                tv_phone_value.setVisibility(GONE);
                tv_role_value.setVisibility(GONE);
                tv_login.setVisibility(VISIBLE);
                tv_logout.setText("登陆");
                tv_edit.setVisibility(GONE);
            }
        } else {
            tv_name_value.setVisibility(GONE);
            tv_phone_value.setVisibility(GONE);
            tv_role_value.setVisibility(GONE);
            tv_login.setVisibility(VISIBLE);
            tv_logout.setText("登陆");
            tv_logout.setTextColor(Color.GREEN);
            tv_edit.setVisibility(GONE);
        }

        tv_logout.setOnClickListener(v -> {
            Intent intent = new Intent(context, LoginActivity.class);
            SharedPreferences.Editor editor = loginInfo.edit();
            editor.clear();   // 清空所有键值对
            editor.apply();   // 或使用 commit()

            SharedPreferences.Editor editor1 = optionParkLot.edit();
            editor1.clear();   // 清空所有键值对
            editor1.apply();   // 或使用 commit()

            //清空所有栈
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.putExtra("online",true);
            context.startActivity(intent);

        });


        return view;
    }

    private void updateUser(User user) {
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_update_user, null);
        EditText editName = dialogView.findViewById(R.id.editName);
        EditText editOriginalPassword = dialogView.findViewById(R.id.editOriginalPassword);
        EditText editNewPassword = dialogView.findViewById(R.id.editNewPassword);
        editName.setText(user.getName());

        AlertDialog dialogHolder = new AlertDialog.Builder(context)
                .setView(dialogView)
                .create();

        Button act = dialogView.findViewById(R.id.btn_action);
        act.setOnClickListener(v -> {

            String name = editName.getText().toString().trim();
            String newPassword = editNewPassword.getText().toString().trim();
            String originalPassword = editOriginalPassword.getText().toString().trim();

            // 简单校验
            if (name.isEmpty()) {
                Toast.makeText(context, "姓名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            int age;

            // 修改基本信息
            user.setName(name);

            // 若用户输入了原密码和新密码，进行密码更新逻辑
            if (!originalPassword.isEmpty() && !newPassword.isEmpty()) {
                if (originalPassword.equals(user.getPassword())) {
                    user.setPassword(newPassword);
                } else {
                    Toast.makeText(context, "原密码不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (!originalPassword.isEmpty() && newPassword.isEmpty() || originalPassword.isEmpty() && !newPassword.isEmpty()) {
                Toast.makeText(context, "密码填写无效", Toast.LENGTH_SHORT).show();
                return;
            }
            userService.updateUser(user);
            Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show();
            tv_name_value.setText(user.getName());
            tv_phone_value.setText(user.getPhone());
            dialogHolder.dismiss();
        });

        dialogHolder.show();
    }
}

